@SuppressLint("StaticFieldLeak")
AsyncTask<Void,String,Void> asyncTask_read = new AsyncTask<Void, String, Void>() {
@Override
protected Void doInBackground(Void... voids) {
try {
InetAddress serverIp = InetAddress.getByName("你的實體IP");
socket_chat = new Socket(serverIp,12345);
// 第一次開啟聊天室
Intent intent_server_change = new Intent("socket_server_change");
intent_server_change.putExtra("socket_server_change", "open");
sendBroadcast(intent_server_change);
// 推到 Progress
br_chat = new BufferedReader(new InputStreamReader(socket_chat.getInputStream()));
String line ;
while((line = br_chat.readLine()) != null) {
publishProgress(line);
}
}catch (Exception k ){
socket_chat = null;
Intent intent_server_change = new Intent("socket_server_change");
intent_server_change.putExtra("socket_server_change","close");
sendBroadcast(intent_server_change);
k.printStackTrace();
}
return null;
};
@Override
protected void onProgressUpdate(String... values) {
if(!values[0].substring(0,2).equals("$$")) {
// 推送訊息
Intent intent_send = new Intent("chat");
intent_send.putExtra("chat",values[0]+"\n");
sendBroadcast(intent_send);
// 暫存訊息,回聊天室畫面時可以傳送
// 也可以不要殺死聊天室的 Activity 就好
if (Chat_str.size() >= 5) {
Chat_str.remove(0);
}
// 聊天室固定加入訊息不暫存
if (!(values[0].equals("**已成功連線,歡迎加入聊天室**"))) {
Chat_str.add(values[0] + "\n");
}
}else {
// 跑馬燈公告
Intent intent_server_change = new Intent("marquee_send");
intent_server_change.putExtra("marquee_send",values[0].substring(2));
sendBroadcast(intent_server_change);
}
super.onProgressUpdate(values);
}
};
asyncTask_read.execute();
if(socket != null && socket.isConnected() ) {
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
BufferedWriter bw ;
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(send_message);
bw.flush();
// 清除 Edittext
Chatedit_clean.sendEmptyMessage(0);
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}else {
Chat.append("聊天伺服器目前關閉中\n");
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}